<!-- 收藏模块 -->
<template>
    <view>
      <el-divider content-position="left">
        <span class="h1">收藏管理</span>
      </el-divider>
      <h1>收藏编辑</h1>
      <br>
      <div>
        <!-- <el-button type="primary" :dark="isDark" plain @click="addData">+ 新增</el-button> -->
        <el-button type="danger" :dark="isDark" plain @click="batchDel">- 批量删除</el-button>
      </div>
      <br>
      <div>
        <el-input v-model="query.postId" placeholder="postId" style="width: 200px"></el-input>
        <el-input v-model="query.title" placeholder="title" style="width: 200px"></el-input>
        <el-input v-model="query.username" placeholder="username" style="width: 200px"></el-input>
        <el-button type="primary" :dark="isDark" plain @click="search">查询</el-button>
        <el-button type="primary" :dark="isDark" plain @click="reset">重置</el-button>
      </div>
      <br>
      <!-- element-plus表格 -->
      <el-table
          ref="tableRef"
          :data="formData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" fixed="left"/>
        <el-table-column prop="postId" label="帖子ID"/>
        <el-table-column prop="userId" label="用户ID"/>
        <el-table-column prop="title" label="标题"/>
        <el-table-column prop="username" label="用户名"/>
        <el-table-column prop="createTime" label="创建时间"/>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <!-- <el-button type="primary" size="small" @click="edit(row)"
            >编辑
            </el-button> -->
            <el-popconfirm
                title="确定要删除吗?"
                @confirm="delData(row)"
                confirm-button-text="是"
                cancel-button-text="否"
            >
              <template #reference>
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <br>
  
      <!-- element-plus分页 -->
      <el-pagination
          v-model:currentPage="query.current"
          :page-size="query.pageSize"
          layout="total,  prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
  
      <!-- 新增/编辑表单 -->
      <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
        <el-form
            :model="formDTO"
            ref="vForm"
            :rules="rules"
            label-position="right"
            label-width="80px"
            size="medium"
            @submit.prevent
        >
          <el-form-item label="ID" prop="favoriteId">
            <el-input v-model="formDTO.favoriteId" type="text" clearable :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="帖子ID" prop="postId">
            <el-input v-model="formDTO.postId" type="text" clearable></el-input>
          </el-form-item>
          <el-form-item label="用户ID" prop="userId">
            <el-input v-model="formDTO.userId" type="text" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submit">提交</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </view>
  </template>
  
  <script setup>
  import {ref, reactive, setDevtoolsHook, onMounted} from "vue";
  import { favorite } from "@/api";
  import { ElNotification } from 'element-plus'
  
  //分页数据
  const pageSize = ref(10);
  const total = ref(0);
  //删除列表
  const delList = ref([]);
  const tableRef = ref();
  //弹出层
  const dialogVisible = ref(false);
  const dialogTitle = ref("");
  const vForm = ref(null);
  
  //表单数据
  const formData = ref([]);
  
  //验证规则
  const rules = ref({
    favoriteId: [
      {
        pattern: /^[-]?\d+(\.\d+)?$/,
        trigger: ["blur", "change"],
        message: "",
      },
    ],
    postId: [
      {
        required: true,
        message: "字段值不可为空",
      },
    ],
    userId: [
      {
        required: true,
        message: "字段值不可为空",
      },
    ],
  });
  
  //提交表单结构
  const formDTO = ref({
    favoriteId: "",
    postId: "",
    userId: "",
  });
  
  //查询参数
  const query = ref({
    current:1,
    pageSize:10,
    postId: "",
    username: "",
    title: "",
  });
  
  
  /**
   * 数据处理-------------------------
   */
  
  /**
   * 编辑
   */
  const edit = (row) => {
    dialogTitle.value = "编辑表单";
    dialogVisible.value = true;
    if (vForm.value) {
      vForm.value.resetFields(); // 确保调用resetFields来重置验证
    }
    // 深拷贝form
    for (let key in formDTO.value) {
      formDTO.value[key] = row[key];
    }
    console.log(row);
  };
  
  /**
   * 删除
   */
  const delData = (row) => {
    del([row.favoriteId])
    console.log(row);
  };
  
  /**
   * 批量删除
   */
  const batchDel = () => {
    del(delList.value);
    console.log(delList.value);
    // 清空选中列表
    tableRef.value.clearSelection();
  };
  
  /**
   * 查询
   */
  const search = () => {
    get(query.value);
  };
  
  /**
   * 重置
   */
  const reset = () => {
    query.value = {
      current:1,
      pageSize:10,
      postId: "",
      username: "",
      title: "",
    };
    get(query.value)
  };
  
  /**
   * 新增
   */
  const addData = () => {
    dialogTitle.value = "新增表单";
    dialogVisible.value = true;
    formDTO.value = {};
    // 重置表单验证状态
    if (vForm.value) {
      vForm.value.resetFields();
    }
  };
  
  /**
   * 提交
   */
  const submit = () => {
    dialogVisible.value = false;
    if (dialogTitle.value === '编辑表单') {
      //调用修改接口
      put(formDTO.value);
    } else {
      //调用添加接口
      add(formDTO.value);
    }
    console.log(formDTO.value);
  };
  
  /**
   * 监听分页
   */
  const handleSizeChange = (val) => {
    query.pageSize.value = val;
    getList();
    console.log(formDTO.value);
  };
  
  /**
   * 选择
   */
  const handleSelectionChange = (val) => {
    //筛出id列表
    delList.value = val.map((item) => item.favoriteId);
    console.log(val);
  };
  
  const handleCurrentChange = (val) =>{
		console.log(val);
		get(query.value)
	}
  
  /**
   * 接口调用------------------------------------------------------------
   */
  
  const add = (data) => {
    console.log("添加数据:", data)
    favorite.add(formDTO.value).then((res) => {
      ElNotification({
        title: 'Success',
        message: '添加成功',
        type: 'success',
      })
			console.log("获取数据:", res.data)
      get(query.value)
		}).catch(err=>{
      ElNotification({
        title: 'Error',
        message: '添加失败',
        type: 'error',
      })
    })
    
  }
  
  const del = (data) => {
    favorite.del(data).then((res) => {
      ElNotification({
        title: 'Success',
        message: '删除成功',
        type: 'success',
      })
			console.log("获取数据:", res.data)
      get(query.value)
		}).catch(err=>{
      ElNotification({
        title: 'Error',
        message: '删除失败',
        type: 'error',
      })
    })
		
  }
  
  const get = (data) => {
    favorite.get(data).then(res=>{
      formData.value = res.data.data.records
			total.value = res.data.data.total
      console.log("获取数据:", res)
    })
    
  }
  
  const put = (data) => {
    favorite.put(data).then(res=>{
      ElNotification({
        title: 'Success',
        message: '编辑成功',
        type: 'success',
      })
			console.log("修改数据:", res)
			get(query.value)
		}).catch(err=>{
      ElNotification({
        title: 'Error',
        message: '编辑失败',
        type: 'error',
      })
    })
  }
  
  
  /**
   * 生命周期
   */
  onMounted(() => {
    get(query.value)
  })
  
  </script>
  
  <style scoped>
  .h1 {
    font-size: 25px;
  }
  </style>
  